/*
 * Copyright 2011 evswork Team
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package org.evswork.getwit.regexp;

import org.evswork.getwit.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;


public class RegExpView extends LinearLayout implements OnClickListener{
	TextView InfoText,ExpText;
	RegExpObject data;
	RegExpListAdapter adapter=null;
	
	public RegExpView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView();
	}

	public RegExpView(Context context) {
		super(context);
		initView();
	}
	
	private void initView() {
		LayoutInflater.from(getContext()).inflate(R.layout.regexp, this,true);
		InfoText = (TextView)this.findViewById(R.id.text1);
		ExpText = (TextView)this.findViewById(R.id.text2);
	}
	
	public void setAdapter(RegExpListAdapter adapter) {
		this.adapter = adapter;
	}
	
	public void update(RegExpObject data) {
		this.data = data;
		
		InfoText.setText(String.format("规则 #%d: (%s)",
				data.pos,
				data.status == RegExpObject.ENABLE ? "启用":
				data.status == RegExpObject.DISABLE ? "禁用":"语法错误"));
		if (data.data.length() == 0)
			ExpText.setText("(空规则)");
		else
			ExpText.setText(data.data);
	}

	@Override
	public void onClick(View v) {
		new AlertDialog.Builder(getContext())
			.setTitle(String.format("规则 #%d", data.pos))
			.setItems(
				new String [] {"启用","禁用","编辑","清空","取消"}, 
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0: // enable
							data.setEnable(true);
							adapter.notifyDataSetChanged();
							break;
						case 1: // disable
							data.setEnable(false);
							adapter.notifyDataSetChanged();
							break;
						case 2: // edit
							makeEditDialog();
							break;
						case 3: // clear
							data.update("");
							adapter.notifyDataSetChanged();
							break;
						case 4: // cancel
							break;
						}
					}
				}
			)
			.show();
	}

	protected void makeEditDialog() {
		new RegExpEditDialogMaker(this,adapter);
	}

	
}
